#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "YaoJiaWen"

from django.shortcuts import render,redirect;
from django.http import JsonResponse;
from util.PageVo import *;
import json;
from util.md5_util import *;
from django.db.models import Q;
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage;
from app_spider.models import *;
from datetime import datetime;

'''
Spider app service
'''

def get_dcbs(request):
    if request.method == "POST":
        search = Search_Vo(json.loads(request.body));
        print(search.__dict__);
        # 使用 keyword 进行模糊匹配
        dcbs = Double_Color_Ball.objects\
            .filter(Q(issue_no__icontains=search.keyword)).order_by(search.sort);

        paginator = Paginator(dcbs, search.page_size);
        try:
            dcbs = paginator.page(search.current_page);
        except PageNotAnInteger as e:
            search.current_page = 1;
            dcbs = paginator.page(1);
        except EmptyPage as e:
            search.current_page= paginator.num_pages;
            dcbs = paginator.page(search.current_page);

        dcb_list = list(user.dcb_dict() for user in dcbs);
        return JsonResponse(Page_Info(
            total=paginator.count,
            pages=paginator.num_pages,
            current_page=search.current_page,
            page_size=search.page_size,
            list=dcb_list
        ).result());
    else:
        return JsonResponse(Result(500, "Unsurport request method.").result());